﻿using MediatR;
using RBAC.Common.Domains;
using RBAC.Common.Dto;
using RBAC.Common.infrastructures.interfaces;
using RBAC.Enum;

namespace RBAC.api.Application.commond.RBAC
{
    public class UserPerssionHander : IRequestHandler<UserPerssionCommond, Rulst>
    {







        private readonly IbaseRpository<User> _user;
        private readonly IbaseRpository<Role> _Rloe;
        private readonly IbaseRpository<userRole> _UserRole;
        private readonly IbaseRpository<Permission> _Permssion;
        private readonly IbaseRpository<RolePermission> _RolePermission;

        public UserPerssionHander(IbaseRpository<User> user, IbaseRpository<Role> rloe, IbaseRpository<userRole> userRole, IbaseRpository<Permission> permssion, IbaseRpository<RolePermission> rolePermission)
        {
            _user = user;
            _Rloe = rloe;
            _UserRole = userRole;
            _Permssion = permssion;
            _RolePermission = rolePermission;
        }

       
        public async Task<Rulst> Handle(UserPerssionCommond request, CancellationToken cancellationToken)
        {
           
            var query= new Rulst() { Code=(int)Reult.success};

            

            var list = (from a in _user.Query()
                        join b in _UserRole.Query() on a.Userid equals b.Userid
                        join c in _Rloe.Query() on b.Roleid equals c.Roleid
                        join d in _RolePermission.Query() on c.Roleid equals d.Roleid
                        join t in _Permssion.Query() on d.Permissionid equals t.Permissionid
                        where a.Userid == request.userid && t.pid==0
                        
                        select new
                        {
                            t.Permissionid,
                            t.PermissionName,
                            t.pid,
                        }).ToList() ;



            var result = list.Where(x => x.pid == x.pid).Select(x => new UserPerssionTree()
            {


                Value = x.Permissionid,
                Name = x.PermissionName,
                Children = _Permssion.Query().Where(t => t.pid == x.Permissionid).Select(s => new UserPerssionTree()
                {
                    Value = s.Permissionid,
                    Name = s.PermissionName,
                    Children = new List<UserPerssionTree>()
                }).ToList()
            });



            if(list!=null)
            {

                query.Code = (int)Reult.success;

                query.data = result;
            }








            return query;



        }
    }
}
